/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim</a>, 2005
 */
package hk.com.carfield.core;

import hk.com.carfield.task.Executor;
import hk.com.carfield.task.ReportService;
import hk.com.carfield.task.ResourceService;
import hk.com.carfield.task.Statist;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.util.TimeUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public final class ScheduleManager {
	private volatile long lastWeeklyRun = 0;

	private volatile long lastDailyRun = 0;

	final Set<Executor> tasks = new HashSet<Executor>();

	ScheduleManager() {
		tasks.add(new Statist());
		tasks.add(new ResourceService());
		tasks.add(new ReportService());
	}

	public void involve(final Context c, final Request r, final File l) throws IOException {
		// TODO add checking if daily and weekly task run or not
		for (final Iterator<Executor> iter = tasks.iterator(); iter.hasNext();) {
			final Executor element = iter.next();
			element.runPerRequest(c, r, l);
		}
		involve(c);
	}

	public void involve(final Context c) {
		final long now = TimeUtil.currentTime();
		if (now - lastDailyRun > TimeUtil.DAY) {
			lastDailyRun = now;
			try {
				for (final Iterator<Executor> iter = tasks.iterator(); iter.hasNext();) {
					final Executor element = iter.next();
					element.runPerDay(c);
				}
			} catch (final IOException e) {
				LogUtil.error(e, c.mailMan);
			}
		}
		if (now - lastWeeklyRun > TimeUtil.WEEK) {
			lastWeeklyRun = now;
			try {
				for (final Iterator<Executor> iter = tasks.iterator(); iter.hasNext();) {
					final Executor element = iter.next();
					element.runPerWeek(c);
				}
			} catch (final IOException e) {
				LogUtil.error(e, c.mailMan);
			}
		}
	}
}